﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using EasySite.Web.Mvc;

namespace EasySite.Web.Caches
{
    public class DefinedControllerCache
    {
        private readonly List<ControllerType> _controllerTypes;
        public List<ControllerType> ControllerTypes
        {
            get { return _controllerTypes; }
        }

        public DefinedControllerCache(Type controllerInstanceType)
        {
            _controllerTypes = new List<ControllerType>();
            var allTypes = controllerInstanceType.Assembly.GetTypes();
            var ignoreMethods = GetMethodNames(typeof(Controller));
            foreach (var type in allTypes)
            {
                if (type.IsPublic && type.Namespace == controllerInstanceType.Namespace)
                {
                    var controllerType = new ControllerType(type.Name);
                    controllerType.Methods = GetMethodNames(type).Where(m => !ignoreMethods.Contains(m)).ToArray();
                    _controllerTypes.Add(controllerType);
                }
            }
        }

        private static IEnumerable<string> GetMethodNames(Type type)
        {
            return type.GetMethods().Where(m => m.IsPublic && m.IsSpecialName == false).Select(m => m.Name).ToArray();
        }
    }

}